package com.luolc.instantmessager.home.conversation;
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 Luolc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;

import com.afollestad.materialdialogs.MaterialDialog;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseConversationListFragment;
import com.hyphenate.util.NetUtils;
import com.luolc.instantmessager.R;
import com.luolc.instantmessager.chat.ChatActivity;
import com.luolc.instantmessager.contact.ContactRepo;
import com.luolc.instantmessager.databinding.ConversationNetErrorItemBinding;
import com.luolc.instantmessager.login.LoginActivity;
import com.luolc.instantmessager.util.UiUtils;

import java.util.List;

import java8.util.stream.Collectors;
import java8.util.stream.StreamSupport;

public class ConversationListFragment extends EaseConversationListFragment {
  private ConversationNetErrorItemBinding binding;

  private final ContactRepo contactRepo;

  public ConversationListFragment() {
    contactRepo = ContactRepo.getInstance();
  }

  @Override
  protected void initView() {
    super.initView();
    binding = DataBindingUtil.inflate(
        LayoutInflater.from(getContext()), R.layout.conversation_net_error_item,
        errorItemContainer, true);
    //noinspection ConstantConditions
    titleBar.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.blue_series_600));
    titleBar.setRightImageResource(R.drawable.home_logout_icon);
    titleBar.setRightLayoutClickListener(v -> showLogoutDialog());
  }

  @SuppressWarnings("ConstantConditions")
  public void showLogoutDialog() {
    new MaterialDialog.Builder(getContext())
        .title("退出登录")
        .content("是否确定退出登录？")
        .positiveText("确定")
        .negativeText("取消")
        .onPositive((dialog, which) -> {
          EMClient.getInstance().logout(true);
          startActivity(new Intent(getContext(), LoginActivity.class));
          getActivity().finish();
        })
        .show();
  }

  @Override
  protected void setUpView() {
    super.setUpView();
    conversationListView.setOnItemClickListener(((parent, view, position, id) -> {
      final EMConversation conversation = conversationListView.getItem(position);
      final String userId = conversation.conversationId();
      if (userId.equals(EMClient.getInstance().getCurrentUser())) {
        UiUtils.toast(getContext(), R.string.conversation_cannot_chat_with_yourself);
      } else {
        final Intent intent = new Intent(getContext(), ChatActivity.class);
        if (conversation.isGroup()) {
          intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_GROUP);
        } else {
          intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        }
        intent.putExtra(EaseConstant.EXTRA_USER_ID, userId);
        startActivity(intent);
      }
    }));
  }

  @Override
  protected void onConnectionDisconnected() {
    super.onConnectionDisconnected();
    if (NetUtils.hasNetwork(getContext())) {
      binding.errorMessage.setText(R.string.conversation_cannot_connect_to_network);
    } else {
      binding.errorMessage.setText(R.string.conversation_current_network_unavailable);
    }
  }

  @Override
  protected List<EMConversation> loadConversationList() {
    final List<EMConversation> conversations = super.loadConversationList();
    final List<String> currentContactIds = StreamSupport.stream(conversations)
        .map(EMConversation::conversationId)
        .collect(Collectors.toList());
    final List<String> userContactIds = StreamSupport.stream(contactRepo.getUserContactIds())
        .filter(id -> !currentContactIds.contains(id))
        .filter(id -> !id.equals(EMClient.getInstance().getCurrentUser()))
        .collect(Collectors.toList());
    final List<EMConversation> toAddUsers = StreamSupport.stream(userContactIds)
        .map(id -> EMClient.getInstance().chatManager().getConversation(
            id, EMConversation.EMConversationType.Chat, true))
        .collect(Collectors.toList());
    final List<EMConversation> toAddGroups = StreamSupport.stream(contactRepo.getGroupContactIds())
        .filter(id -> !currentContactIds.contains(id))
        .map(id -> EMClient.getInstance().chatManager().getConversation(
            id, EMConversation.EMConversationType.GroupChat, true))
        .collect(Collectors.toList());
    conversations.addAll(toAddUsers);
    conversations.addAll(toAddGroups);
    return conversations;
  }
}
